package com.itboye.textileexpres.main;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.itboye.textileexpes.beans.CollectionCateTypeModel;
import com.itboye.textileexpes.beans.ColletionFenyeBeans;
import com.itboye.textileexpes.beans.ColletionFenyeBeans.InfoBeans;
import com.itboye.textileexpes.presenter.AppUpdatePresenter;
import com.itboye.textileexpes.presenter.ColloctionPresenter;
import com.itboye.textileexpres.R;
import com.itboye.textileexpres.base.BaseFragment;
import com.itboye.textileexpres.base.ResultEntity;
import com.itboye.textileexpres.base.SpPublicParams;
import com.itboye.textileexpres.collection.ActivityCollectionEdit;
import com.itboye.textileexpres.collection.ActivityCollectionSeaech;
import com.itboye.textileexpres.collection.CollectionGoodsListViewAdapter;
import com.itboye.textileexpres.collection.CollectionGoodsListViewAdapter.onLikeFavorites;
import com.itboye.textileexpres.collection.CollectionGridAdapter;
import com.itboye.textileexpres.login.LoginActivity;
import com.itboye.textileexpres.myset.ActivityCustomerService;
import com.itboye.textileexpres.top.GoodsDetail;
import com.itboye.textileexpres.util.IsMobileNumPhone;
import com.itboye.textileexpres.util.MyToast;
import com.itboye.textileexpres.util.SPUtils;
import com.itboye.textileexpres.widget.MyGridView;
import com.itboye.textileexpres.widget.XListView;
import com.itboye.textileexpres.widget.XListView.IXListViewListener;
/**
 * 订单
 *
 */
public class CollectionFragment extends BaseFragment implements
		OnClickListener, Observer, IXListViewListener, onLikeFavorites {
	ImageView back;
	TextView title;
	MyGridView type_grid;
	XListView goods_list;
	ImageView load_more_img;
	int Default_show = 2;
	int cloums = 4;
	boolean mIsShrink = true;
	TextView edit;
	CollectionGoodsListViewAdapter listViewAdapter;
	CollectionGridAdapter gridAdapter;
	EditText key_word;
	ColloctionPresenter colloctionPresenter;
	String uid;
	// ColletionFenyeBeans list;
	int pagesize = 1;
	ColletionFenyeBeans beans = new ColletionFenyeBeans();
	List<ColletionFenyeBeans.InfoBeans> list = new ArrayList<ColletionFenyeBeans.InfoBeans>();
	List<CollectionCateTypeModel> cateTypeModels = new ArrayList<CollectionCateTypeModel>();
	String type = "clean";
	ImageView img_search;
	ImageView img_other;
	RelativeLayout null_collect;
	ScrollView scroll_layout;
	TextView goods_num;
	RelativeLayout load_more_lin;
	String viewtype = "listview";
	String cateID;
	boolean ista;
	AppUpdatePresenter appUpdatePresenter;

	@Override
	public int initView() {
		// TODO Auto-generated method stub
		return R.layout.fragment_collection;
	}

	@Override
	public void onMyActivityCreated() {
		// TODO Auto-generated method stub
		title.setText(R.string.collection);
		back.setVisibility(View.GONE);
		img_search.setVisibility(View.GONE);
		img_other.setVisibility(View.VISIBLE);
		appUpdatePresenter=new AppUpdatePresenter(this);
		img_other.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if ("".equals(IsMobileNumPhone.isUid())
						|| IsMobileNumPhone.isUid() == null) {
					Intent intent = new Intent(getActivity(),
							LoginActivity.class);
					startActivity(intent);
				} else {
					Intent intent = new Intent(getActivity(),
							ActivityCustomerService.class);
					startActivity(intent);
				}
			}
		});
		uid = (String) SPUtils.get(getActivity(), null, SpPublicParams.UID, "");
		IntentFilter filter = new IntentFilter("UpDateCollection");
		IntentFilter exitfilter = new IntentFilter("newshead");
		IntentFilter loginfilter = new IntentFilter("LoginSuccess");
		getActivity().registerReceiver(broadcastReceiver, filter);
		getActivity().registerReceiver(exitReceiver, exitfilter);
		getActivity().registerReceiver(broadcastReceiver, loginfilter);
		colloctionPresenter = new ColloctionPresenter(this);
		if ("".equals(uid) || uid == "") {
			NullCollect();
			// Intent intent = new Intent(getActivity(), LoginActivity.class);
			// startActivity(intent);
		} else {
			VisibleCollect();
			colloctionPresenter.FenYeQuery(uid, "15", pagesize + "", "", "",
					"1");
			colloctionPresenter.CollectionCateType(uid);
			goods_list.setPullLoadEnable(true);
			goods_list.setPullRefreshEnable(true);
			goods_list.setXListViewListener(this);

			load_more_img.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (mIsShrink) {
						expand();
					} else {
						collapse();
					}
					setListViewHeightBasedOnChildren(type_grid);
				}
			});
			setListViewHeightBasedOnChildren(type_grid);
			goods_list.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					// TODO Auto-generated method stub
					if (arg2 - 1 >= 0) {
						try {
							Intent intent = new Intent(getActivity(),
									GoodsDetail.class);
							intent.putExtra("pid", list.get(arg2 - 1)
									.getFavorite_id());
							startActivity(intent);
						} catch (Exception e) {
							// TODO: handle exception

						}

					}

				}
			});
		}
		img_other.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if ("".equals(uid) || uid == "") {
					Intent intent = new Intent(getActivity(),
							LoginActivity.class);
					startActivity(intent);
				} else {
					Intent intent = new Intent(getActivity(),
							ActivityCustomerService.class);
					startActivity(intent);
					
				}

			}
		});
		type_grid.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				cateID = cateTypeModels.get(arg2).getCate_id();
				viewtype = "gridview";
				type = "gride";
				showProgressDialog(getString(R.string.loading),true);
				if(ista){
					ista=false;
					colloctionPresenter.FenYeQuery(uid, "15", "1", "",
							"", "1");
				}else{
					ista=true;
					colloctionPresenter.FenYeQuery(uid, "15", "1", "",
							cateID, "1");
				}
				
			}
		});
	}

	void NullCollect() {
		scroll_layout.setVisibility(View.GONE);
		goods_list.setVisibility(View.GONE);
		type_grid.setVisibility(View.GONE);
		null_collect.setVisibility(View.VISIBLE);
	}

	void VisibleCollect() {
		scroll_layout.setVisibility(View.VISIBLE);
		goods_list.setVisibility(View.VISIBLE);
		type_grid.setVisibility(View.VISIBLE);
		null_collect.setVisibility(View.GONE);
	}

	BroadcastReceiver exitReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			list.clear();
			try {
				uid = (String) SPUtils.get(getActivity(), null,
						SpPublicParams.UID, "") + "";
			} catch (Exception e) {
				// TODO: handle exception
			}

			NullCollect();
		}
	};
	BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			try {
				uid = (String) SPUtils.get(getActivity(), null,
						SpPublicParams.UID, "") + "";
			} catch (Exception e) {
				// TODO: handle exception
			}
			list.clear();
			colloctionPresenter.FenYeQuery(uid, "15", 1 + "", "", "", "1");
			colloctionPresenter.CollectionCateType(uid);
		}
	};
	OnClickListener toTopClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			ColletionFenyeBeans model = new ColletionFenyeBeans();
			model.setUid(uid);
			model.setIds(list.get((Integer) v.getTag()).getId());
			colloctionPresenter.update(model);
			listViewAdapter.notifyDataSetChanged();
		}
	};

	@SuppressWarnings("unchecked")
	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		ResultEntity entity = super.handlerError(data);
		if (entity != null) {
			if (entity.getEventType() == ColloctionPresenter.ColloctFenye_success) {
				if (type.equals("load")) {

				} else {
					list.clear();
				}
				beans = (ColletionFenyeBeans) entity.getData();
				list.addAll(beans.getList());
				listViewAdapter = new CollectionGoodsListViewAdapter(
						getActivity(), list, toTopClickListener, this);
				goods_list.setAdapter(listViewAdapter);
				goods_num.setText(beans.getCount() + "");
				setListViewHeightBasedOnChildren(goods_list);
				load_more_img.setVisibility(View.VISIBLE);
				if (list == null || list.size() == 0) {
					NullCollect();
				} else {
					VisibleCollect();
				}
				listViewAdapter.notifyDataSetChanged();
				stop();
				try {
					closeProgressDialog();
				} catch (Exception e) {
					// TODO: handle exception
				}
			} else if (entity.getEventType() == ColloctionPresenter.ColloctFenye_fail) {
				// MyToast.toast("" + entity.getData());

			}
			if (entity.getEventType() == ColloctionPresenter.ColloctCate_success) {
				cateTypeModels.clear();
				cateTypeModels
						.addAll((Collection<? extends CollectionCateTypeModel>) entity
								.getData());
				if (cateTypeModels.size() > 8) {
					gridAdapter = new CollectionGridAdapter(getActivity(),
							cateTypeModels, 8);
				} else {
					gridAdapter = new CollectionGridAdapter(getActivity(),
							cateTypeModels, cateTypeModels.size());
					load_more_lin.setVisibility(View.GONE);
				}
				type_grid.setAdapter(gridAdapter);
				// beans = (ColletionFenyeBeans) entity.getData();

			} else if ((entity.getEventType() == ColloctionPresenter.ColloctCate_fail)) {
				// MyToast.toast("" + entity.getData());
			}
			if (entity.getEventType() == ColloctionPresenter.ColloctTop_success) {
				MyToast.toast(getString(R.string.h1206));
				colloctionPresenter.FenYeQuery(uid, "15", pagesize + "", "",
						"", "1");
				listViewAdapter.notifyDataSetChanged();
			} else if (entity.getEventType() == ColloctionPresenter.ColloctTop_fail) {
				MyToast.toast(getString(R.string.h1207));
			}
			if (entity.getEventType() == ColloctionPresenter.Add_success) {
				list.clear();
				colloctionPresenter.FenYeQuery(uid, "15", pagesize + "", "",
						"", "1");
				colloctionPresenter.CollectionCateType(uid);
				listViewAdapter.notifyDataSetChanged();
				
				if(entity.getData().equals("操作成功")){
					toast(getString(R.string.Cancel_collection));// 取消收藏
				}else{
					toast(getString(R.string.h1187));// 取消收藏
				}
			} else if (entity.getEventType() == ColloctionPresenter.Add_fai) {
				MyToast.toast("" + entity.getData());
			}
		} else
		
		
		try {
			closeProgressDialog();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent = null;
		switch (v.getId()) {
		case R.id.edit:
			intent = new Intent(getActivity(), ActivityCollectionEdit.class);
			
			startActivity(intent);
			break;
		case R.id.img_other:
			intent = new Intent(getActivity(), ActivityCustomerService.class);
			startActivity(intent);
			break;
		case R.id.key_word:
			intent = new Intent(getActivity(), ActivityCollectionSeaech.class);
			startActivity(intent);
			break;
		default:
			break;
		}
	}

	// 收缩
	private void collapse() {
		// TODO Auto-generated method stub
		if (cateTypeModels.size() > 8) {
			gridAdapter = new CollectionGridAdapter(getActivity(),
					cateTypeModels, 8);
		} else {
			gridAdapter = new CollectionGridAdapter(getActivity(),
					cateTypeModels, cateTypeModels.size());
		}

		type_grid.setAdapter(gridAdapter);
		mIsShrink = true;
		load_more_img.setImageResource(R.drawable.collect_up);
		gridAdapter.notifyDataSetChanged();
	}

	// 展开
	private void expand() {
		// TODO Auto-generated method stub
		gridAdapter = new CollectionGridAdapter(getActivity(), cateTypeModels,
				cateTypeModels.size());
		// mlist = mList;
		type_grid.setAdapter(gridAdapter);
		mIsShrink = false;
		load_more_img.setImageResource(R.drawable.collect_down);
		gridAdapter.notifyDataSetChanged();
	}

	public void setListViewHeightBasedOnChildren(ListView listView) {
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			return;
		}
		int totalHeight = 0;
		for (int i = 0; i < listAdapter.getCount(); i++) {
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();
		}
		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight
				+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		listView.setLayoutParams(params);
	}

	protected void setListViewHeightBasedOnChildren(GridView gridview) {
		if (gridview == null)
			return;
		ListAdapter listAdapter = gridview.getAdapter();
		if (listAdapter == null)
			return;
		int totalHeight = 0;
		int count = (int) Math.ceil(listAdapter.getCount() / 4.0);
		View itemView = listAdapter.getView(0, null, gridview);
		itemView.measure(0, 0);
		totalHeight = itemView.getMeasuredHeight();
		ViewGroup.LayoutParams params = gridview.getLayoutParams();
		params.height = (dpTopx(10) + totalHeight) * count;
		gridview.setLayoutParams(params);
	}

	private int dpTopx(int dp) {
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
				getResources().getDisplayMetrics());
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		type = "clean";
		pagesize = 1;
		viewtype = "listview";
		colloctionPresenter.FenYeQuery(uid, "15", pagesize + "", "", "", "1");
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		type = "load";
		pagesize++;
		if ("gridview".equals(viewtype)) {
			ista=false;
			colloctionPresenter.FenYeQuery(uid, "15", pagesize + "", "",
					cateID, "1");
		} else {
			ista=true;
			colloctionPresenter.FenYeQuery(uid, "15", pagesize + "", "", "",
					"1");
		}

	}

	void stop() {
		goods_list.stopLoadMore();
		goods_list.stopRefresh();
	}

	@Override
	public void onLikeFavoer(View v) {
		// TODO Auto-generated method stub
		String id = list.get((Integer) v.getTag()).getFavorite_content()
				.getId();
		colloctionPresenter.onAddLike(uid, id, "1");// (list);
		listViewAdapter.notifyDataSetChanged();
	}
}
